package com.lx.exceptionHandler;/*
package com.lx.exceptionHandler;

import com.lx.util.Result;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExceptionHandler {
    @org.springframework.web.bind.annotation.ExceptionHandler(Throwable.class)
    public Result handleException(Throwable e) {
        return Result.error(4000, e.getMessage());
    }

}
*/


import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import com.lx.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestControllerAdvice
public class GlobalExceptionHandler {

    public static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = {RuntimeException.class})
    public void ExceptionHandler(RuntimeException e,HttpServletResponse response) {
        log.error(e.getMessage(), e);
        ObjectMapper objectMapper = new ObjectMapper();
        response.setStatus(500);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        try {
            response.getWriter().write(objectMapper.writeValueAsString(Result.error(4000, e.getMessage())));
            response.getWriter().flush();
            response.getWriter().close();
        } catch (JsonProcessingException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}
